package com.ruoyi.leave.service.impl;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.leave.entity.LeaveInfo;
import com.ruoyi.leave.repository.LeaveInfoRepository;
import com.ruoyi.leave.service.LeaveInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.lsjscl.flowboot.common.ResponseData;
import vip.lsjscl.flowboot.util.DeleteStrategyService;
import vip.lsjscl.flowboot.util.constants.TaskStatus;
import vip.lsjscl.flowboot.workflow.service.DKWorkflowService;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Transactional
@Service
public class LeaveInfoServiceImpl implements LeaveInfoService {

    @Autowired
    private LeaveInfoRepository leaveInfoRepository;

    @Autowired
    private DKWorkflowService workflowService;

    @Autowired
    private DeleteStrategyService deleteStrategyService;

    @Override
    public ResponseData getMyApplications(Map<String, Object> params) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        // 获取当前用户的所有申请
        List<LeaveInfo> applications = leaveInfoRepository.findAllByCreateByOrderByCreateTimeDesc(userId.toString());
        return ResponseData.ok().put("data", applications);
    }

    @Override
    public ResponseData getTodoTasks() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 根据业务ID列表查询对应的请假信息
        List<Object[]> todoTasks = leaveInfoRepository.findListByUserIdOrDeptIdAndStatus(String.valueOf(loginUser.getUserId()), String.valueOf(loginUser.getDeptId()), TaskStatus.PENDING.getCode());

        List<LeaveInfo> collect = todoTasks.stream().map(result -> {
            //转为LeaveInfo
            LeaveInfo leaveInfo = new LeaveInfo();
            leaveInfo.setId(result[0].toString());
            leaveInfo.setName(result[7].toString());
            leaveInfo.setReason(result[8].toString());
            leaveInfo.setStartDate(DateUtils.parseDate(result[5]));
            leaveInfo.setEndDate(DateUtils.parseDate(result[6]));
            leaveInfo.setStatus(result[10].toString());
            leaveInfo.setWorkflowVersionId(result[11].toString());
            leaveInfo.setTaskId(result[13].toString());
            return leaveInfo;
        }).collect(Collectors.toList());
        return ResponseData.ok().put("data", collect);
    }

    @Override
    public ResponseData getDoneTasks(List<String> businessIds) {
        if (businessIds.isEmpty()) {
            return ResponseData.ok().put("data", List.of());
        }

        // 根据业务ID列表查询对应的请假信息
        List<LeaveInfo> doneTasks = leaveInfoRepository.findAllById(businessIds);
        return ResponseData.ok().put("data", doneTasks);
    }

    @Override
    public ResponseData submitLeaveApplication(LeaveInfo leaveInfo) {
        try {
            // 设置状态为待处理
            leaveInfo.setStatus("PENDING");
            LeaveInfo saved = leaveInfoRepository.save(leaveInfo);
            // 初始化工作流，传入业务ID
            String leave = workflowService.startWorkflow("leave", saved.getId());
            saved.setWorkflowVersionId(leave);
            return ResponseData.ok().put("data", saved);
        }
        catch (Exception e) {
            return ResponseData.error("提交申请失败");
        }
    }


    @Override
    public ResponseData saveOrUpdate(LeaveInfo leaveInfo) {
        try {
            LeaveInfo saved = leaveInfoRepository.save(leaveInfo);
            return ResponseData.ok().put("data", saved);
        }
        catch (Exception e) {
            return ResponseData.error("保存失败");
        }
    }

    @Override
    public ResponseData getLeaveDetail(String id) {
        try {
            Optional<LeaveInfo> optionalLeave = leaveInfoRepository.findById(id);
            if (optionalLeave.isEmpty()) {
                return ResponseData.error("申请不存在");
            }
            return ResponseData.ok().put("data", optionalLeave.get());
        }
        catch (Exception e) {
            return ResponseData.error("获取详情失败");
        }
    }

    @Override
    public ResponseData deleteLeaveApplication(String id) {
        try {
            Optional<LeaveInfo> optionalLeave = leaveInfoRepository.findById(id);
            if (optionalLeave.isEmpty()) {
                return ResponseData.error("申请不存在");
            }

            LeaveInfo leaveInfo = optionalLeave.get();
            // 只能删除草稿状态的申请
            if (!"DRAFT".equals(leaveInfo.getStatus())) {
                return ResponseData.error("只能删除草稿状态的申请");
            }

            deleteStrategyService.delete(leaveInfoRepository, id);
            return ResponseData.ok();
        }
        catch (Exception e) {
            return ResponseData.error("删除失败");
        }
    }
} 